/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.loja.model.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author DavidLuiz
 */
public class MapDAO<E> implements IDAO<Map.Entry<Integer, E>> {

    private int key = 0;
    private final Map<Integer, E> map;
    private final List<E> database;

    public MapDAO(List<E> database) {
        this.database = database;
        this.map = getMap(database);
    }

    private Map<Integer, E> getMap(List<E> database) {
        Map<Integer, E> m = new HashMap<>();
        for (E e : database) {
            m.put(key++, e);
        }
        return m;
    }

    private void updateDataBase() {
        database.clear();
        database.addAll(map.values());
    }

    @Override
    public Map.Entry<Integer, E> save(Map.Entry<Integer, E> entity) {
        map.put(entity.getKey(), entity.getValue());
        updateDataBase();
        return entity;
    }

    @Override
    public List<Map.Entry<Integer, E>> list(boolean cacheable) {
        List<Map.Entry<Integer, E>> list = new ArrayList<>();
        for (Map.Entry<Integer, E> entrySet : map.entrySet()) {
            list.add(entrySet);
        }
        return list;
    }

    @Override
    public void remove(Map.Entry<Integer, E> entity) {
        if (map.containsKey(entity.getKey())) {
            map.remove(entity.getKey());
            updateDataBase();
        }
    }

    @Override
    public void update(Map.Entry<Integer, E> entity) {
        for (Map.Entry<Integer, E> entrySet : map.entrySet()) {
            if (entity.getKey().equals(entrySet.getKey())) {
                entrySet.setValue(entity.getValue());
                updateDataBase();
                break;
            }
        }
    }

    @Override
    public Map.Entry<Integer, E> findByPrimaryKey(Object pk) {
        for (Map.Entry<Integer, E> entrySet : map.entrySet()) {
            if (entrySet.getKey().equals(pk)) {
                return entrySet;
            }
        }
        return null;
    }

    @Override
    public List<Map.Entry<Integer, E>> list(Map<String, ?> properties, boolean cacheable) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}
